package com.cskaoyan.demo1.servlet;

import com.cskaoyan.demo1.bean.MarketStorage;
import com.cskaoyan.demo1.mapper.MarketStorageMapper;
import com.cskaoyan.demo1.util.JsonUtil;
import com.cskaoyan.demo1.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @Description：
 * @Author：BLUEBLANK
 * @Date：2024/4/7 13:31
 */

@WebServlet("/admin/storage/create")
@MultipartConfig
public class AdminStorageServlet extends HttpServlet {
    String storagePath;
    String urlPrefix;

    // 利用adminStorageServlet的初始化，进行唯一的一次加载
    // 有get 就要有set    setAttribute 是要在另一个servlet里面进行设置
    @Override
    public void init() throws ServletException {
        storagePath = (String) getServletContext().getAttribute("storagePath");
        urlPrefix = (String) getServletContext().getAttribute("urlPrefix");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // getPart("与前端保持一致")
        // postman 设置post  file
        // index.html
//         <form action="/demo3/admin/storage/create" enctype="multipart/form-data" method="post">
//                 用户：<input type="text" name="username"><br>
//                 密码：<input type="password" name="password"><br>
//                 头像：<input type="file" name="avatar"><br>
//     <input type="submit">
// </form>
        Part part = req.getPart("file");
        // ikun.jpg
        String submittedFileName = part.getSubmittedFileName();
        // 获取文件名 后缀  例如 .jpg
        String suffix = submittedFileName.substring(submittedFileName.indexOf("."));
        // 处理key 唯一标识
        String uuidStr = UUID.randomUUID().toString();
        String key = uuidStr.replace("-", "").concat(suffix);


        String contentType = part.getContentType();
        long size = part.getSize();

        // url
        String url = urlPrefix + key;

        InputStream in = part.getInputStream();

        File file = new File(storagePath,submittedFileName);
        FileOutputStream out = new FileOutputStream(file);

        byte[] bytes = new byte[1024];
        int len;
        while ((len = in.read(bytes)) != -1) {
            out.write(bytes,0,len);
        }
        out.close();

        // 存入数据库
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        MarketStorageMapper mapper = sqlSession.getMapper(MarketStorageMapper.class);
        MarketStorage marketStorage = new MarketStorage(null, key, submittedFileName, contentType, ((int) size), url, new Date(), new Date(), false);

        mapper.insertSelective(marketStorage);

        // 获取json语句
        String jsonStr = JsonUtil.write(marketStorage);

        // 打印json语句
        ServletOutputStream outputStream = resp.getOutputStream();
        outputStream.write(jsonStr.getBytes());



    }
}
